#include <vector>
#include <algorithm>
#include <functional>
#include "board.h"
#include "abstract_pin.h"

namespace arduino {

namespace {
	struct pin_equal : std::unary_function<abstract_pin, bool>
	{
		const unsigned int pin_number;
		pin_equal(unsigned int n) : pin_number(n) {}
		bool operator()(const abstract_pin* other) const
		{
			return other->pin_number() == pin_number;
		}
	};
} // anonymous namespace

void board::register_pin(abstract_pin* pin)
{
	pins_.push_back(pin);
}

abstract_pin* board::pin(int pin_number)
{
	pin_collection_type::iterator it = find_if(pins_.begin(), pins_.end(), pin_equal(pin_number));

	if (it != pins_.end()) {
		return *it;
	}

	return NULL;
}

void board::setup()
{
	for (auto it = pins_.begin(); it != pins_.end(); ++it) {
		if ((*it)->initialize()) {
			(*it)->brd_ = this;
		}
	}

	//for_each(pins_.begin(), pins_.end(), std::mem_fun(&abstract_pin::initialize));
}

DWORD board::send(void* msg, DWORD len)
{
	return ser_->write(msg, len);
}

} // namespace arduino
